<template>
  <el-dialog
      v-model="visible"
      title="批量训练"
      width="900px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <div class="batch-training-container">
      <!-- 快速设置区域 -->
      <div class="quick-setup-section">
        <el-card class="setup-card">
          <template #header>
            <div class="setup-header">
              <span>快速设置分类</span>
              <el-button
                  type="primary"
                  size="small"
                  :disabled="!quickCategory.primary || !quickCategory.secondary"
                  @click="applyQuickCategory"
              >
                应用到所有
              </el-button>
            </div>
          </template>

          <div class="quick-category-selector">
            <div class="category-row">
              <el-select
                  v-model="quickCategory.primary"
                  placeholder="选择一级分类"
                  style="width: 200px;"
                  @change="handleQuickPrimaryChange"
              >
                <el-option
                    v-for="category in categories.primary"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                />
              </el-select>

              <el-select
                  v-model="quickCategory.secondary"
                  placeholder="选择二级分类"
                  style="width: 200px;"
                  :disabled="!quickCategory.primary"
                  @change="handleQuickSecondaryChange"
              >
                <el-option
                    v-for="category in quickSecondaryOptions"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                />
              </el-select>

              <el-select
                  v-model="quickCategory.tertiary"
                  placeholder="选择三级分类（可选）"
                  style="width: 200px;"
                  :disabled="!quickCategory.secondary"
                  clearable
              >
                <el-option
                    v-for="category in quickTertiaryOptions"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                />
              </el-select>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 任务列表 -->
      <div class="tasks-section">
        <div class="tasks-header">
          <span>训练任务列表 ({{ selectedRecords.length }}个)</span>
          <div class="header-actions">
            <el-button @click="selectAllTasks">全选</el-button>
            <el-button @click="unselectAllTasks">取消全选</el-button>
          </div>
        </div>

        <div class="tasks-list">
          <div
              v-for="(record, index) in taskList"
              :key="record.task_id"
              class="task-item"
              :class="{
                'disabled': !record.enabled,
                'training': record.training,
                'completed': record.trainingCompleted,
                'failed': record.trainingFailed
              }"
          >
            <div class="task-content">
              <div class="task-checkbox">
                <el-checkbox
                    v-model="record.enabled"
                    :disabled="record.training || record.trainingCompleted"
                />
              </div>

              <div class="task-preview">
                <el-image
                    v-if="record.preview_url"
                    :src="basePythonURL2 + record.preview_url"
                    fit="cover"
                    style="width: 60px; height: 45px; border-radius: 4px;"
                />
                <div v-else class="preview-placeholder">
                  <el-icon><VideoCamera /></el-icon>
                </div>
              </div>

              <div class="task-info">
                <div class="task-name">{{ record.output_name || '未命名' }}</div>
                <div class="task-files">
                  <span>{{ record.human_name }}</span> + <span>{{ record.background_name }}</span>
                </div>
              </div>

              <div class="task-category">
                <div class="category-selectors">
                  <el-select
                      v-model="record.category.primary"
                      placeholder="一级分类"
                      size="small"
                      style="width: 120px;"
                      :disabled="record.training || record.trainingCompleted"
                      @change="handlePrimaryChange(index)"
                  >
                    <el-option
                        v-for="category in categories.primary"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                    />
                  </el-select>

                  <el-select
                      v-model="record.category.secondary"
                      placeholder="二级分类"
                      size="small"
                      style="width: 120px;"
                      :disabled="!record.category.primary || record.training || record.trainingCompleted"
                      @change="handleSecondaryChange(index)"
                  >
                    <el-option
                        v-for="category in record.secondaryOptions"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                    />
                  </el-select>

                  <el-select
                      v-model="record.category.tertiary"
                      placeholder="三级分类"
                      size="small"
                      style="width: 120px;"
                      :disabled="!record.category.secondary || record.training || record.trainingCompleted"
                      clearable
                  >
                    <el-option
                        v-for="category in record.tertiaryOptions"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                    />
                  </el-select>
                </div>
              </div>

              <div class="task-status">
                <div v-if="record.training" class="status-training">
                  <el-icon class="rotating"><Loading /></el-icon>
                  <span>训练中...</span>
                </div>
                <div v-else-if="record.trainingCompleted" class="status-completed">
                  <el-icon><Check /></el-icon>
                  <span>已完成</span>
                </div>
                <div v-else-if="record.trainingFailed" class="status-failed">
                  <el-icon><Close /></el-icon>
                  <span>失败</span>
                </div>
                <div v-else-if="record.category.primary && record.category.secondary" class="status-ready">
                  <el-icon><Select /></el-icon>
                  <span>就绪</span>
                </div>
                <div v-else class="status-pending">
                  <el-icon><Warning /></el-icon>
                  <span>待设置</span>
                </div>
              </div>
            </div>

            <!-- 进度条 -->
            <div v-if="record.training" class="task-progress">
              <el-progress
                  :percentage="record.progress || 0"
                  :show-text="false"
                  stroke-width="4"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 训练进度汇总 -->
      <div v-if="isTraining" class="training-summary">
        <el-card>
          <div class="summary-content">
            <div class="summary-stats">
              <div class="stat-item">
                <span class="stat-label">总数:</span>
                <span class="stat-value">{{ enabledTasks.length }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">已完成:</span>
                <span class="stat-value completed">{{ completedCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">失败:</span>
                <span class="stat-value failed">{{ failedCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">进行中:</span>
                <span class="stat-value training">{{ trainingCount }}</span>
              </div>
            </div>
            <div class="overall-progress">
              <el-progress
                  :percentage="overallProgress"
                  :color="overallProgressColor"
              />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="isTraining">取消</el-button>
        <el-button
            type="primary"
            :loading="isTraining"
            :disabled="!canStartTraining"
            @click="startBatchTraining"
        >
          {{ isTraining ? '训练中...' : '开始批量训练' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api, { basePythonURL2 } from '@/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  selectedRecords: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'training-complete'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 响应式数据
const categories = ref({
  primary: [],
  secondary: [],
  tertiary: []
})

const quickCategory = ref({
  primary: null,
  secondary: null,
  tertiary: null
})

const taskList = ref([])
const isTraining = ref(false)
const loading = ref(false)

// 计算属性
const quickSecondaryOptions = computed(() => {
  if (!quickCategory.value.primary) return []
  const primary = categories.value.primary.find(c => c.id === quickCategory.value.primary)
  return primary?.children || []
})

const quickTertiaryOptions = computed(() => {
  if (!quickCategory.value.secondary) return []
  const secondary = quickSecondaryOptions.value.find(c => c.id === quickCategory.value.secondary)
  return secondary?.children || []
})

const enabledTasks = computed(() => {
  return taskList.value.filter(task => task.enabled)
})

const canStartTraining = computed(() => {
  return enabledTasks.value.length > 0 &&
      enabledTasks.value.every(task =>
          task.category.primary && task.category.secondary
      ) && !isTraining.value
})

const completedCount = computed(() => {
  return taskList.value.filter(task => task.trainingCompleted).length
})

const failedCount = computed(() => {
  return taskList.value.filter(task => task.trainingFailed).length
})

const trainingCount = computed(() => {
  return taskList.value.filter(task => task.training).length
})

const overallProgress = computed(() => {
  if (enabledTasks.value.length === 0) return 0
  const finishedCount = completedCount.value + failedCount.value
  return Math.round((finishedCount / enabledTasks.value.length) * 100)
})

const overallProgressColor = computed(() => {
  if (failedCount.value > 0) return '#f56c6c'
  if (completedCount.value === enabledTasks.value.length) return '#67c23a'
  return '#409eff'
})

// 监听对话框打开
watch(visible, async (newVal) => {
  if (newVal) {
    await loadCategories()
    initTaskList()
  }
})

// 方法
const loadCategories = async () => {
  loading.value = true
  try {
    const result = await api.getCategoryTree()
    if (result.code === 200) {
      categories.value.primary = result.data.map(item => ({
        id: item.id,
        name: item.name,
        level: item.level,
        children: item.children || []
      }))
    }
  } catch (error) {
    ElMessage.error('加载分类失败')
  } finally {
    loading.value = false
  }
}

const initTaskList = () => {
  taskList.value = props.selectedRecords.map(record => ({
    ...record,
    enabled: true,
    training: false,
    trainingCompleted: false,
    trainingFailed: false,
    progress: 0,
    category: {
      primary: null,
      secondary: null,
      tertiary: null
    },
    secondaryOptions: [],
    tertiaryOptions: []
  }))
}

const handleQuickPrimaryChange = async () => {
  quickCategory.value.secondary = null
  quickCategory.value.tertiary = null
}

const handleQuickSecondaryChange = async () => {
  quickCategory.value.tertiary = null
}

const applyQuickCategory = () => {
  taskList.value.forEach((task, index) => {
    if (task.enabled && !task.training && !task.trainingCompleted) {
      // 先设置一级分类并更新选项
      task.category.primary = quickCategory.value.primary
      handlePrimaryChange(index)

      // 然后设置二级分类并更新选项
      if (quickCategory.value.secondary) {
        task.category.secondary = quickCategory.value.secondary
        handleSecondaryChange(index)

        // 最后设置三级分类
        if (quickCategory.value.tertiary) {
          task.category.tertiary = quickCategory.value.tertiary
        }
      }
    }
  })
  ElMessage.success('分类设置已应用到所有任务')
}

const handlePrimaryChange = (index) => {
  const task = taskList.value[index]
  task.category.secondary = null
  task.category.tertiary = null

  const primary = categories.value.primary.find(c => c.id === task.category.primary)
  task.secondaryOptions = primary?.children || []
  task.tertiaryOptions = []
}

const handleSecondaryChange = (index) => {
  const task = taskList.value[index]
  task.category.tertiary = null

  const secondary = task.secondaryOptions.find(c => c.id === task.category.secondary)
  task.tertiaryOptions = secondary?.children || []
}

const selectAllTasks = () => {
  taskList.value.forEach(task => {
    if (!task.training && !task.trainingCompleted) {
      task.enabled = true
    }
  })
}

const unselectAllTasks = () => {
  taskList.value.forEach(task => {
    if (!task.training && !task.trainingCompleted) {
      task.enabled = false
    }
  })
}

const startBatchTraining = async () => {
  if (!canStartTraining.value) {
    ElMessage.warning('请确保所有任务都已设置分类')
    return
  }

  isTraining.value = true
  const tasks = enabledTasks.value.filter(task => !task.trainingCompleted && !task.trainingFailed)

  let successCount = 0
  let failedCount = 0

  try {
    // 串行执行训练任务
    for (const task of tasks) {
      task.training = true
      task.progress = 10

      try {
        // 模拟进度更新
        const progressInterval = setInterval(() => {
          if (task.progress < 90) {
            task.progress += Math.random() * 10
          }
        }, 1000)

        const result = await api.startTraining({
          taskId: task.task_id,
          videoPath: task.result_path,
          primaryCategoryId: task.category.primary,
          secondaryCategoryId: task.category.secondary,
          tertiaryCategoryId: task.category.tertiary || 0,
          modelName: task.output_name,
        })

        clearInterval(progressInterval)

        if (result.success) {
          task.progress = 100
          task.trainingCompleted = true
          successCount++
        } else {
          task.trainingFailed = true
          failedCount++
        }
      } catch (error) {
        task.trainingFailed = true
        failedCount++
      } finally {
        task.training = false
      }
    }

    // 发送完成事件
    emit('training-complete', {
      success: true,
      successCount,
      failedCount,
      totalCount: tasks.length
    })

  } catch (error) {
    ElMessage.error('批量训练过程中发生错误')
    emit('training-complete', {
      success: false,
      message: error.message
    })
  } finally {
    isTraining.value = false
  }
}

const handleClose = () => {
  if (isTraining.value) {
    ElMessage.warning('训练进行中，无法关闭')
    return
  }
  visible.value = false
  // 重置状态
  taskList.value = []
  quickCategory.value = {
    primary: null,
    secondary: null,
    tertiary: null
  }
}
</script>

<style lang="scss" scoped>
.batch-training-container {
  max-height: 70vh;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.quick-setup-section {
  .setup-card {
    .setup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .quick-category-selector {
      .category-row {
        display: flex;
        gap: 15px;
        align-items: center;
      }
    }
  }
}

.tasks-section {
  flex: 1;
  overflow: hidden;

  .tasks-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    font-weight: 500;

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .tasks-list {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 10px;
  }
}

.task-item {
  margin-bottom: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;

  &:last-child {
    margin-bottom: 0;
  }

  &.disabled {
    opacity: 0.6;
    background-color: #f5f7fa;
  }

  &.training {
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  &.completed {
    border-color: #67c23a;
    background-color: #f0f9ff;
  }

  &.failed {
    border-color: #f56c6c;
    background-color: #fef0f0;
  }

  .task-content {
    display: flex;
    align-items: center;
    padding: 15px;
    gap: 15px;

    .task-checkbox {
      flex-shrink: 0;
    }

    .task-preview {
      flex-shrink: 0;

      .preview-placeholder {
        width: 60px;
        height: 45px;
        background: #f5f7fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #c0c4cc;
      }
    }

    .task-info {
      flex: 1;
      min-width: 0;

      .task-name {
        font-weight: 500;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .task-files {
        font-size: 12px;
        color: #909399;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .task-category {
      flex-shrink: 0;

      .category-selectors {
        display: flex;
        gap: 8px;
      }
    }

    .task-status {
      flex-shrink: 0;
      min-width: 80px;

      .status-training,
      .status-completed,
      .status-failed,
      .status-ready,
      .status-pending {
        display: flex;
        align-items: center;
        gap: 5px;
        font-size: 12px;
      }

      .status-training {
        color: #409eff;
      }

      .status-completed {
        color: #67c23a;
      }

      .status-failed {
        color: #f56c6c;
      }

      .status-ready {
        color: #67c23a;
      }

      .status-pending {
        color: #e6a23c;
      }
    }
  }

  .task-progress {
    padding: 0 15px 15px;
  }
}

.training-summary {
  .summary-content {
    .summary-stats {
      display: flex;
      gap: 30px;
      margin-bottom: 15px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 5px;

        .stat-label {
          color: #606266;
          font-size: 14px;
        }

        .stat-value {
          font-weight: 500;
          font-size: 16px;

          &.completed {
            color: #67c23a;
          }

          &.failed {
            color: #f56c6c;
          }

          &.training {
            color: #409eff;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .quick-category-selector .category-row {
    flex-direction: column;
    align-items: stretch;

    .el-select {
      width: 100% !important;
    }
  }

  .task-content {
    flex-direction: column;
    align-items: stretch !important;
    gap: 10px !important;

    .task-category .category-selectors {
      flex-direction: column;

      .el-select {
        width: 100% !important;
      }
    }
  }

  .summary-stats {
    flex-direction: column !important;
    gap: 10px !important;
  }
}
</style>